﻿#include "epibolyroutine.h"
#include "ui_epibolyroutine.h"

EpibolyRoutine::EpibolyRoutine(QWidget *parent,const QString &_batch) :
    QDialog(parent),
    ui(new Ui::EpibolyRoutine)
{
    ui->setupUi(this);
    batch=_batch;

    ui->lbl_batch->setText(QStringLiteral("批次：") + batch);

    model=new QSqlTableModel(this);
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);

    ui->tableView->setModel(model);
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
}

EpibolyRoutine::~EpibolyRoutine()
{
    delete ui;
}

void EpibolyRoutine::updateView()
{
    model->setTable("td_epiboly_routine");
    model->setFilter(QString("batch = '%1'").arg(batch));
    model->select();

    model->setHeaderData(0,Qt::Horizontal,QStringLiteral("ID"));
    model->setHeaderData(1,Qt::Horizontal,QStringLiteral("日期"));
    model->setHeaderData(2,Qt::Horizontal,QStringLiteral("批次"));
    model->setHeaderData(3,Qt::Horizontal,QStringLiteral("名称"));
    model->setHeaderData(4,Qt::Horizontal,QStringLiteral("数量"));
    model->setHeaderData(5,Qt::Horizontal,QStringLiteral("备注"));
}

bool EpibolyRoutine::saveRecord()
{
    QSqlQuery query;
    query.prepare("insert into td_epiboly_routine (date,batch,name,number,remark) values (?,?,?,?,?)");
    query.addBindValue(Env::date);
    query.addBindValue(batch);
    query.addBindValue(name);
    query.addBindValue(number);
    query.addBindValue(remark);
    return query.exec();
}

void EpibolyRoutine::on_submit_clicked()
{
    name=ui->name->text().trimmed();
    if(name.isEmpty() || ui->number->text().isEmpty())
    {
        QMessageBox::warning(this,QStringLiteral("不能为空"),QStringLiteral("名称、数量不能为空！"),QMessageBox::Ok);
    }
    else
    {
        number=ui->number->text();
        remark=ui->remark->text();
        if(saveRecord())
        {
            updateView();
            ui->name->clear();
            ui->number->clear();
            ui->remark->clear();
            ui->lbl_status->setText(QStringLiteral("记录已提交"));
        }
        else
            ui->lbl_status->setText(QStringLiteral("提交失败！数据库异常"));
    }
}

void EpibolyRoutine::on_save_clicked()
{
    model->submitAll();
}

void EpibolyRoutine::closeEvent(QCloseEvent *)
{
    emit accept();
}
